﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.IO.Ports;

using RexToy;
using RexToy.Copy;
using RexToy.Logging;

namespace MGAS.Model
{
    sealed class SensorDataCollector : ISensorDataCollector
    {
        private static ILog _log = LogContext.GetLogger<SensorDataCollector>();

        private Communicator _com;
        private List<byte> _sensorIds;
        public SensorDataCollector()
        {
            InitializeAddressList();
            _com = new Communicator();
        }

        private ISensorDataBlock _target;
        public ISensorDataBlock Target
        {
            get { return _target; }
            set { _target = value; }
        }

        Thread _tWork;
        bool _doWork;
        public void StartCollect()
        {
            _com.Open();
            _doWork = true;
            _tWork = new Thread(Work);
            _tWork.Name = "CollectorWorker";
            _tWork.Start();
        }

        public void StopCollect()
        {
            _doWork = false;
            if (_tWork != null)
                _tWork.Join();
            _com.Close();
        }

        private void Work()
        {
            _log.Info("Worker thread start collect data.");
            while (_doWork)
            {
                Thread.Sleep(Configuration.GetPollingLatency());
                foreach (var id in _sensorIds)
                {
                    if (!_doWork)
                        break;

                    var data = _com.Query(id, false);//Note:During polling, we don't need meta info.
                    _target.UpdateData(data.ID, data.Value, data.Unit, data.Status);
                }
            }
            _log.Info("Worker thread stop collect data.");
        }

        public void InitializeAddressList()
        {
            _sensorIds = new List<byte>(AllocMap.Instance().GetSensorIds());
        }
    }
}
